import { get, post, postJson, postFile } from "../utils/request";
import app from '../utils/cloudbase';

// 确保登录状态的函数
async function ensureLogin() {
  const auth = app.auth();
  await auth.signInAnonymously();
}

//分页查询
export function page(params) {
  return new Promise((resolve, reject) => {
    ensureLogin().then(() => {
      app.callFunction({
        name: 'Book',
        data: {
          action: 'getBooks',
          page: params.pageNum,
          pageSize: params.pageSize,
          keyword: params.goodsName || '',
          category: params.category || '',
          status: params.status || ''
        }
      }).then(res => {
        console.log('云函数返回数据:', res)
        // 直接返回原始响应，让组件处理数据结构
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    }).catch(err => {
      reject(err)
    })
  })
}

//新增或更新
export function save(params) {
  return new Promise((resolve, reject) => {
    ensureLogin().then(async () => {
      try {
        // 标准化数据格式
        const bookData = {
          name: params.book.name,
          author: params.book.author,
          category: params.book.category,
          description: params.book.description,
          price: Number(params.book.price),
          stock: Number(params.book.stock),
          status: params.book.status,
          img: params.book.img,
          sale: Number(params.book.sale || 0)
        };

        // 验证必填字段
        const requiredFields = ['name', 'author', 'category', 'price', 'stock', 'status'];
        const missingFields = requiredFields.filter(field => !bookData[field] && bookData[field] !== 0);
        if (missingFields.length > 0) {
          throw new Error(`缺少必填字段: ${missingFields.join(', ')}`);
        }

        // 验证数据类型
        if (isNaN(bookData.price) || bookData.price < 0) {
          throw new Error('价格必须是非负数');
        }
        if (isNaN(bookData.stock) || bookData.stock < 0) {
          throw new Error('库存必须是非负数');
        }
        if (!['上架', '下架', '缺货'].includes(bookData.status)) {
          throw new Error('状态必须是 上架、下架 或 缺货');
        }

        // 构造请求数据 - 根据云函数的参数结构调整
        const requestData = {
          action: params.id ? 'updateBook' : 'addBook'
        };

        if (params.id) {
          // 更新操作
          requestData.bookId = params.id;
          requestData.data = bookData;  // updateBook函数期望第二个参数是data
        } else {
          // 新增操作
          requestData.book = bookData;  // addBook函数期望参数是book
        }

        console.log('发送到云函数的数据:', requestData);

        // 调用云函数
        const res = await app.callFunction({
          name: 'Book',
          data: requestData
        });

        console.log('云函数返回结果:', res);

        if (res.result && res.result.code === 200) {
          resolve(res);
        } else {
          throw new Error(res.result?.message || '保存失败');
        }
      } catch (err) {
        console.error('保存失败:', err);
        reject(err);
      }
    }).catch(err => {
      console.error('认证失败:', err);
      reject(err);
    });
  });
}

//删除
export function deleteByIds(ids) {
  return new Promise((resolve, reject) => {
    ensureLogin().then(() => {
      // 如果是数组，只取第一个ID（因为云函数只支持单个删除）
      const bookId = Array.isArray(ids) ? ids[0] : ids;
      
      app.callFunction({
        name: 'Book',
        data: {
          action: 'deleteBook',
          bookId: bookId
        }
      }).then(res => {
        if (res.result && res.result.code === 200) {
          resolve(res);
        } else {
          reject(new Error(res.result?.message || '删除失败'));
        }
      }).catch(err => {
        reject(err);
      });
    }).catch(err => {
      reject(err);
    });
  });
}

// 图片上传
export function uploadPic(file) {
  return new Promise((resolve, reject) => {
    ensureLogin().then(() => {
      const fileName = `${Date.now()}-${file.name}`;
      app.uploadFile({
        cloudPath: `book_images/${fileName}`,
        filePath: file
      }).then(res => {
        // 只返回文件名，不返回完整路径
        resolve({ data: { data: fileName } });
      }).catch(err => {
        reject(err);
      });
    }).catch(err => {
      reject(err);
    });
  });
}

// 保存多张图片
export function savePics(pics, id) {
  return new Promise((resolve, reject) => {
    ensureLogin().then(() => {
      app.callFunction({
        name: 'Book',
        data: {
          action: 'updateBook',
          bookId: id,
          data: {
            pics: pics
          }
        }
      }).then(res => {
        resolve({ data: res.result });
      }).catch(err => {
        reject(err);
      });
    }).catch(err => {
      reject(err);
    });
  });
}

//根据商店id查询商品并排序
export function getGoodsPx({ dateRange }) {
  return new Promise((resolve, reject) => {
    ensureLogin().then(() => {
      app.callFunction({
        name: 'Book',
        data: {
          action: 'getHotBooks',
          dateRange
        }
      }).then(res => {
        resolve({ data: res.result });
      }).catch(err => {
        reject(err);
      });
    }).catch(err => {
      reject(err);
    });
  });
}